package com.blog.dazi.Service;

import jdk.nashorn.internal.runtime.ECMAException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class HistoryService {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    public List<Map<String, Object>> findByTel(String tel) {
        String sql = "select b.tag,b.count from sys_user a,sys_user_search_history b where a.id = b.user_id and a.phone_number = ? ORDER BY b.count desc limit 5";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql, tel);
        return maps;
    }

    public int save(String tel, String tag) {
        String sql = "select id from sys_user where phone_number = ?";
        Integer userId = jdbcTemplate.queryForObject(sql, Integer.class, tel);

        String sql2 = "select count from sys_user_search_history where user_id = ? and tag = ? ";
        try {
            Map<String, Object> map = jdbcTemplate.queryForMap(sql2, userId,tag);
            Integer count = (Integer) map.get("count");
            String sql3 = "update sys_user_search_history set count = ? where user_id = ? and tag = ? ";
            return jdbcTemplate.update(sql3,count+1,userId,tag);
        }catch (Exception e){
            String sql3 = "insert into sys_user_search_history (user_id,tag,count) values (?,?,?)";
            return jdbcTemplate.update(sql3,userId,tag,1);
        }

    }
}
